package com.yytek.am.core.runtime;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import com.yytek.am.constants.AkkaConstants;
import com.yytek.am.core.ActorConfig;
import com.yytek.am.core.rule.EventRule;
import com.yytek.am.core.rule.EventRuleClear;
import com.yytek.am.core.rule.EventRuleGenerate;
import com.yytek.am.core.rule.EventRuleWrapper;
import com.yytek.common.client.base.MqConfig;

import java.util.List;

public class EngineRuntime {
	private RuleManager ruleManager;
	private EventIOManager eventIOManager;
	private ActorRef ioActor;
	private ActorRef eventManager;

	private boolean inited = false;

	public EngineRuntime() {
		ActorSystem system = ActorConfig.createAndGetActorSystem();
		//初始化告警定义缓存
		eventManager = system.actorOf(EventManager.props());
		ruleManager = new RuleManager(eventManager);
		ioActor = system.actorOf(EventSourceSinkActor.props(eventManager, ruleManager),
				EventSourceSinkActor.class.getName());
		eventIOManager = new EventIOManager(ioActor);
	}

	/**
	 * 初始化告警计算引擎
	 * @param eventRuleWrappers
	 * @param mqConfig
	 * @param topicList
	 */
	public void init(List<EventRuleWrapper> eventRuleWrappers, MqConfig mqConfig, List<String> topicList) {
		if (!inited) {
			// 初始化告警定义 根据对象中的信息将生成，清除规则写入对应的eventManager中
			for (EventRuleWrapper eventRuleWrapper : eventRuleWrappers) {
				EventRule eventRule = eventRuleWrapper.getEventRule();
				if (eventRule != null) {
					ruleManager.updateEventRule(AkkaConstants.EventRuleUpdateType.UPDATE, eventRule);
				}
				EventRuleGenerate eventRuleGenerate = eventRuleWrapper.getEventRuleGenerate();
				if (eventRuleGenerate != null) {
					ruleManager.updateEventRuleGenerate(AkkaConstants.EventRuleUpdateType.UPDATE, eventRuleGenerate);
				}
				EventRuleClear eventRuleClear = eventRuleWrapper.getEventRuleClear();
				if (eventRuleClear != null) {
					ruleManager.updateEventRuleClear(AkkaConstants.EventRuleUpdateType.UPDATE, eventRuleClear);
				}
			}
			// 初始化监听告警源
			eventIOManager.addSource(mqConfig, topicList);
			inited = true;
		}

	}

}
